#include "stackapp.h"

extern func_LinkStack fun_LinkStack;

/**
 * 功 能：
 *      进制转换
 * 参 数：
 *      num :要转换的数字，为十进制
 *      base:基数，要转换的进制
 *      out :转换结果输出
 * 返回值：
 *      成功：0
 *      失败：-1
 **/
int StackApp_Conversion(int num, char base, char *out)
{
    if (base <= 1 || base > 16 || out == NULL)
        return -1;

    LinkStack *stack = fun_LinkStack.create();
    if (stack == NULL)
        return -1;

    char temp = 0;

    while (num)
    {
        temp = num % base;
        /* 将 temp 转换为字符 */
        if (temp > 10)
            temp += 0x37;
        else
            temp += 0x30;

        fun_LinkStack.push(stack, (LinkListNode *)(long)(temp));
        num = num / base;
    }

    char *buf = (char *)malloc(fun_LinkStack.length(stack) + 1);
    char *pbuf = buf;
    memset(buf, 0, fun_LinkStack.length(stack) + 1);

    while (fun_LinkStack.length(stack) > 0 && num == 0)
    {
        char tnum = (char)(long)fun_LinkStack.pop(stack);
        // printf("%c ", tnum);
        strncpy(pbuf, (const char *)&tnum, 1);
        pbuf++;
    }

    // printf("buf = %s \n", buf);
    if (out != NULL)
        strcpy(out, buf);

    free(buf);
    buf = NULL;
    pbuf = NULL;

    return 0;
}

func_StackApp fun_StackApp = {
    StackApp_Conversion};
